package com.youlu.campus.service.qa;

import com.youlu.campus.entity.ActivityQaRule;
import com.youlu.campus.entity.VO.req.CopyActivityQaRuleReq;
import com.youlu.campus.entity.VO.req.DailyAttendanceQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityQaRuleService {

    @Autowired
    private MongoTemplate mongoTemplate;


    public List<ActivityQaRule> findByActivityId(String activityId){
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        return this.mongoTemplate.find(query,ActivityQaRule.class);
    }

    @Async
    public void doCopyQaRule(CopyActivityQaRuleReq copyActivityQaRuleReq){
        String copyActivityId = copyActivityQaRuleReq.getCopyActivityId();
        String copyActivityQaInfoId = copyActivityQaRuleReq.getCopyActivityQaInfoId();
        log.info("【copy 活动题库答题规则】开始复制活动答题规则 sourceActivityId->{} | copyActivityQaInfoId->{}",copyActivityId, copyActivityQaInfoId);
        Query query = new Query();
        query.addCriteria(Criteria.where("activityQaInfoId").is(copyActivityQaInfoId));
        query.addCriteria(Criteria.where("activityId").is(copyActivityId));
        List<ActivityQaRule> activityQaRuleList = this.mongoTemplate.find(query, ActivityQaRule.class);
        if(CollectionUtils.isEmpty(activityQaRuleList)){
            log.error("【copy 活动题库答题规则】复制活动答题规则未查询到数据 sourceActivityId->{} | copyActivityQaInfoId->{}",copyActivityId, copyActivityQaInfoId);
            return;
        }
        Date now = new Date();
        List<ActivityQaRule> targetQaRuList = activityQaRuleList.stream().peek(activityQaRule -> {
            activityQaRule.setId(null);
            activityQaRule.setActivityId(copyActivityQaRuleReq.getTargetCopyActivityId());
            activityQaRule.setActivityQaInfoId(copyActivityQaRuleReq.getTargetActivityQaInfoId());
            activityQaRule.setCreatedTime(now);
            activityQaRule.setUpdatedTime(now);
        }).collect(Collectors.toList());
        this.mongoTemplate.insertAll(targetQaRuList);
        log.info("【copy 活动题库答题规则】开始复制活动答题规则 sourceActivityId->{} | copyActivityQaInfoId->{}",copyActivityId, copyActivityQaInfoId);

    }
}
